package com.samsung.sbackup;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class RebootReceiver extends BroadcastReceiver {
	SharedPreferences sharedPref;

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		if ((intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))) {
			sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
			AlarmManager alarmManager = (AlarmManager) context
					.getSystemService(Activity.ALARM_SERVICE);
			Intent i = new Intent(context, AlarmReceiver.class);
			PendingIntent pendingIntent = PendingIntent.getBroadcast(
					context.getApplicationContext(), 0, i,
					PendingIntent.FLAG_UPDATE_CURRENT);
			long t = Long.valueOf(Convert(sharedPref.getString(
					FragmentSettingsPreference.BACKUP_TIME, "")));
			if (sharedPref.getBoolean(
					FragmentSettingsPreference.SCHEDULE_BACKUP, false)) {

				if (Long.valueOf(Convert(sharedPref.getString(
						FragmentSettingsPreference.BACKUP_TIME, ""))) < java.lang.System
						.currentTimeMillis()) {
					t = Long.valueOf(Convert(sharedPref.getString(
							FragmentSettingsPreference.BACKUP_TIME, "")))
							+ sharedPref.getInt(
									FragmentSettingsPreference.REPEATATION, 1)
							* 1000 * 24 * 3600;

				}
				alarmManager
						.setRepeating(AlarmManager.RTC_WAKEUP, t, Long
								.valueOf(sharedPref.getInt(
										FragmentSettingsPreference.REPEATATION,
										1)) * 1000 * 24 * 3600, pendingIntent);

			} else {
				alarmManager.cancel(pendingIntent);
			}
		}

	}

	public String Convert(String string) {
		String input = string;
		Date date = null;
		try {
			date = new SimpleDateFormat("dd-MM-yyyy HH:mm", Locale.getDefault())
					.parse(input);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		long milliseconds = date.getTime();
		return String.valueOf(milliseconds);
	}

}
